﻿import {  Component,  EventEmitter, Injector, Output, ViewChild } from '@angular/core';
import { AppComponentBase } from '@shared/common/app-component-base';
import { OrganizationUnitDto, PasswordComplexitySetting, ProfileServiceProxy,  UserRoleDto, UserServiceProxy,UsingFormDetailExeInput } from '@shared/service-proxies/service-proxies';
import { ModalDirective } from 'ngx-bootstrap';
import * as _ from 'lodash';
import { finalize } from 'rxjs/operators';
import { TestDataDto,UsingFormServiceProxy,UsingFormState,RoleUserServiceProxy } from '@shared/service-proxies/service-proxies';
import { AbpSessionService } from '@abp/session/abp-session.service';
@Component({
    selector: 'requirementGetAuditEditComponent',
    templateUrl: './requirement-get-audit_edit.component.html'
})
export class RequirementGetAuditEditComponent extends AppComponentBase {

    @ViewChild('createOrEditModal') modal: ModalDirective;

    @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();

    active = false;
    saving = false;
    canChangeUserName = true;
    isTwoFactorEnabled: boolean = this.setting.getBoolean('Abp.Zero.UserManagement.TwoFactorLogin.IsEnabled');
    isLockoutEnabled: boolean = this.setting.getBoolean('Abp.Zero.UserManagement.UserLockOut.IsEnabled');
    passwordComplexitySetting: PasswordComplexitySetting = new PasswordComplexitySetting();

    //user: UserEditDto = new UserEditDto();
    usingFormDto: TestDataDto = new TestDataDto();
    roles: UserRoleDto[];
    sendActivationEmail = true;
    setRandomPassword = true;
    passwordComplexityInfo = '';
    profilePicture: string;

    allOrganizationUnits: OrganizationUnitDto[];
    memberedOrganizationUnits: string[];
    editFlag = true;
    usingFormDtoStateOption: object[];// 审核状态
    usingFormDetailId: number;
    userId: string;
    state: number;
    //formDetail: UsingFormDetailExeInput;
    authorityUserOption: Array<object>;

    constructor(
        injector: Injector,
        private _userService: UserServiceProxy,
        private _usingFormServiceProxy: UsingFormServiceProxy,
        private _roleUserServiceProxy: RoleUserServiceProxy,
        private _sessionServiceProxy: AbpSessionService,
        private _profileService: ProfileServiceProxy
    ) {
        super(injector);
        this.usingFormDtoStateOption = new Array();
        this.usingFormDtoStateOption.push({ value: 0, text: UsingFormState[0] });
        this.usingFormDtoStateOption.push({ value: 1, text: UsingFormState[1] });
        this.usingFormDtoStateOption.push({ value: 2, text: UsingFormState[2] });
        this.usingFormDtoStateOption.push({ value: 3, text: UsingFormState[3] });
    }
    /**
     * 获取有权限的用户
     */
    getAuthorityUserOption(_pState) {
        this.authorityUserOption = new Array<object>()
        //生产处审批人 = 1,
        this._roleUserServiceProxy.getUsersByRole(_pState)
            .pipe(finalize(() => this.primengTableHelper.hideLoadingIndicator())).subscribe(result => {
                this.authorityUserOption = result;
            });
    }
    show(_pUsingFormDetailId: number, _pState: UsingFormState): void {
        if (_pState == 4 || _pState == 0) {
            return;
        } else if (_pState == 1) {
            this.state = 2;
        } else if (_pState == 2) {
            this.state = 3;
        } else if (_pState == 3) {
            this.state = 4;
        }
        this.usingFormDetailId = _pUsingFormDetailId;
        this.userId = "";
        // 用户角色 也流程状态差1
        this.getAuthorityUserOption(_pState);
        this.active = true;
        this.modal.show();
    }


    getProfilePicture(profilePictureId: string): void {
        if (!profilePictureId) {
            this.profilePicture = this.appRootUrl() + 'assets/common/images/default-profile-picture.png';
        } else {
            this._profileService.getProfilePictureById(profilePictureId).subscribe(result => {

                if (result && result.profilePicture) {
                    this.profilePicture = 'data:image/jpeg;base64,' + result.profilePicture;
                } else {
                    this.profilePicture = this.appRootUrl() + 'assets/common/images/default-profile-picture.png';
                }
            });
        }
    }

    onShown(): void {
        //document.getElementById('userid').focus();
    }
    /**
     * 校验
     */
    toCheck(): void {
        var usingFormDetailExeInput = new UsingFormDetailExeInput();
        usingFormDetailExeInput.id = this.usingFormDetailId;
        usingFormDetailExeInput.userId = this.userId;
        this._usingFormServiceProxy.toCheck(usingFormDetailExeInput)
            .pipe(finalize(() => { }))
            .subscribe(() => {
                this.notify.info(this.l('SavedSuccessfully'));
                this.close();
                this.modalSave.emit(null);
            });
    }
    /**
     * 需求领用出库
     * @param record 
     */
    toExecute() {
        this.primengTableHelper.showLoadingIndicator();
        var formToDoInput = new UsingFormDetailExeInput();
        formToDoInput.id = this.usingFormDetailId;
        formToDoInput.userId = this.userId;
        this._usingFormServiceProxy.toExecute(formToDoInput)
            .pipe(finalize(() => this.primengTableHelper.hideLoadingIndicator())).subscribe(result => {
                this.primengTableHelper.hideLoadingIndicator();
                this.notify.info(this.l('SavedSuccessfully'));
                this.close();
                this.modalSave.emit(null);
                //this.getUsingFormList();
            });
    }
    /**
     * 完成申请单
     * @param record 
     */
    toFinish() {
        this.primengTableHelper.showLoadingIndicator();
        var formToDoInput = new UsingFormDetailExeInput();
        formToDoInput.id = this.usingFormDetailId;
        formToDoInput.userId = this.userId;
        this._usingFormServiceProxy.toFinish(formToDoInput)
            .pipe(finalize(() => this.primengTableHelper.hideLoadingIndicator())).subscribe(result => {
                this.primengTableHelper.hideLoadingIndicator();
                this.notify.info(this.l('SavedSuccessfully'));
                this.close();
                this.modalSave.emit(null);
            });
    }
    save(): void {
        if (this.state == 2) {
            this.toCheck();
        } else if (this.state == 3) {
            // 出库
            this.toExecute();
        } else if (this.state == 4) {
            // 完成
            this.toFinish();
        }
    }

    close(): void {
        this.active = false;
        this.modal.hide();
    }

    getAssignedRoleCount(): number {
        return _.filter(this.roles, { isAssigned: true }).length;
    }
}
